package com.liuwei.msmall.order.web;

import com.alipay.api.AlipayApiException;
import com.liuwei.msmall.order.config.AlipayTemplate;
import com.liuwei.msmall.order.entity.OrderEntity;
import com.liuwei.msmall.order.service.OrderService;
import com.liuwei.msmall.order.vo.PayAsyncVo;
import com.liuwei.msmall.order.vo.PaySuccessVo;
import com.liuwei.msmall.order.vo.PayVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Objects;

@Controller
public class PayWebController {

    @Autowired
    AlipayTemplate alipayTemplate;
    @Autowired
    OrderService orderService;


    //去支付页面
    @ResponseBody
    @GetMapping(value = "/order/pay",produces = "text/html")
    public String payOrder(String orderSn) throws AlipayApiException {
        //准备订单的支付信息
        PayVo vo = orderService.getOrderPayInfo(orderSn);

        if (Objects.isNull(vo)){
            return "<h1>订单已过期</h1>";
        }

        //拿到响应结果，是一个html类型的表单
        String pay = alipayTemplate.pay(vo);

        return pay;
    }

    //去支付成功页面
    @GetMapping("/pay/success.html")
    public String paySuccess(PayAsyncVo vo, Model model){

        PaySuccessVo successVo = new PaySuccessVo();
        String orderSn = vo.getOut_trade_no();
        successVo.setOrderSn(orderSn);
        successVo.setPayPrice(new BigDecimal(vo.getTotal_amount()));
        //获取订单信息
        OrderEntity order = orderService.getOrderByOrderSn(orderSn);

        //设置收货信息
        successVo.setReceiverName(order.getReceiverName());
        successVo.setReceiverCity(order.getReceiverCity());
        successVo.setReceiverDetailAddress(order.getReceiverDetailAddress());
        successVo.setReceiverPhone(order.getReceiverPhone());
        successVo.setReceiverProvince(order.getReceiverProvince());
        successVo.setReceiverRegion(order.getReceiverRegion());
        model.addAttribute("data",successVo);
        return "success";
    }


}
